<script lang="ts" setup>
import { getNoteContent, saveNoteContent, uploadImageToOSS } from '@/api/study/ossApi';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { message } from 'ant-design-vue';
import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';

const props = defineProps({
  courseId: {
    type: String,
    required: true,
  },
  sourceId: {
    type: String,
    required: true,
  },
  resourceType: {
    type: String,
    required: true,
  },
});

// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref('');

// 获取笔记内容的函数
const loadNoteContent = async () => {
  try {
    const response = await getNoteContent(props.courseId, props.sourceId, props.resourceType);
    // 将 HTML 内容赋值到编辑器中
    valueHtml.value = response.noteContent;
    if (editorRef.value)
      editorRef.value.setHtml(valueHtml.value); // 确保编辑器初始化后设置内容
  }
  catch (error) {
    console.error('获取笔记内容失败:', error);
  }
};

// 初次挂载时获取内容
onMounted(loadNoteContent);

// 监听 courseId 和 sourceId 的变化
watch(
  () => [props.courseId, props.sourceId],
  () => {
    loadNoteContent();
  },
);

const toolbarConfig = {
  excludeKeys: ['emotion', 'group-video'], // 排除表情和视频
};

const editorConfig = {
  withCredentials: true,
  placeholder: '在这里留下学习过程中的巧思吧！',
  MENU_CONF: {
    uploadImage: {
      async customUpload(file: File, insertFn: (url: string) => void) {
        try {
          // 使用阿里云 OSS 客户端上传文件
          const result = await uploadImageToOSS(file);
          if (result && result.url) {
            // 将上传后的URL插入到编辑器中
            insertFn(result.url);
          }
        }
        catch (error) {
          console.error('图片上传失败:', error);
          message.error('图片上传失败，请检查网络连接或配置。');
        }
      },
    },
  },
};

const mode = 'default';

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null)
    return;
  editor.destroy();
});

// 编辑器回调函数
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  if (valueHtml.value)
    editor.setHtml(valueHtml.value); // 在编辑器创建完成后设置初始内容
};

// 保存笔记内容
const save = async () => {
  const editor = editorRef.value;
  if (editor == null)
    return;

  try {
    await saveNoteContent(props.courseId, props.sourceId, editor.getHtml(), props.resourceType);
    message.success('笔记保存成功');
  }
  catch (error) {
    console.error('保存笔记失败:', error);
  }
};

const exportDoc = () => {
  const editor = editorRef.value;
  if (editor == null)
    return;

  const parser = new DOMParser();
  const htmlContent = editor.getHtml();
  const parsedHtml = parser.parseFromString(htmlContent, 'text/html');

  const images = parsedHtml.querySelectorAll('img');

  // 处理图片，将其转换为Base64并嵌入HTML中
  images.forEach((img) => {
    const imageSrc = img.src;
    const imgElement = new Image();
    imgElement.src = imageSrc;
    imgElement.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = imgElement.width;
      canvas.height = imgElement.height;
      const ctx = canvas.getContext('2d');

      // 检查 ctx 是否为 null
      if (ctx) {
        ctx.drawImage(imgElement, 0, 0);
        const base64Image = canvas.toDataURL('image/jpeg');
        img.setAttribute('src', base64Image); // 替换为Base64编码
      }
      else {
        console.error('无法获取Canvas 2D上下文');
      }
    };
  });

  // 创建一个包含文本和图片的HTML字符串
  const modifiedHtml = parsedHtml.body.innerHTML;
  const blob = new Blob([modifiedHtml], { type: 'application/msword' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = 'note.doc';
  link.click();
};
</script>

<template>
  <div class="editor-wrapper">
    <div class="toolbar">
      <button class="share-button" @click="save">
        保存
      </button>
      <button class="export-button" @click="exportDoc">
        导出
      </button>
    </div>
    <div class="toolbar-container">
      <Toolbar
        :editor="editorRef"
        :default-config="toolbarConfig"
        :mode="mode"
        class="toolbar-style"
      />
    </div>
    <div class="editor-container">
      <Editor
        v-model:html="valueHtml"
        :default-config="editorConfig"
        :mode="mode"
        style="height: 70vh; overflow-y: hidden"
        @on-created="handleCreated"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.editor-wrapper {
  padding: 15px;
  border-radius: 8px;
  width: 100%;
  height: calc(100vh - 70px);
  overflow-x: hidden;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-bottom: 10px;
  margin-top: -10px;
}

.share-button, .export-button {
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 20px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.share-button {
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
}

.export-button {
  background-color: #6697fe;
  color: #ffffff;
  border: none;
}

.share-button:hover {
  background-color: #e6e6e6;
}

.export-button:hover {
  background-color: #357ab8;
}

.toolbar-container {
  border-bottom: 1px solid #ccc;
}

.toolbar-style {
  color: #000000; /* 设置工具栏字体颜色为黑色 */
}

.editor-container {
  border: 1px solid #ccc;
  margin-top: 10px;
}
</style>
